import { delAttachmentUrl, addAttachment } from "@/api/sys/attachment";
import { uploadAttachment } from "@/api/hrp/user";
import { isHttp } from '@/utils/validate'


const useAttachmentStore = defineStore(
  'attachment',

  {
    state: () => ({
      urls: [],
      uploadfiles: [],
      delurls: [],
    }),
    actions: {
      //上传文件并将返回值记录在附件表 返回json字符串
      async uploadAttachments() {
        if (this.uploadfiles.length > 0) {
          await this.uploadfiles.reduce(async (prev, item) => {
            await prev;
            const response = await uploadAttachment(item.file)
            item.from.fileUrl = response.url
            this.addurl(response.url)
            const res = await addAttachment(item.from)
            console.log(res);
          }, 0);
          this.urls = this.urls.filter((cur) => {
            delete cur.uid
            delete cur.status
            return cur.url.indexOf('blob:') == -1 && isHttp(cur.url)
          })
        }

        return JSON.stringify(this.urls)
      },
      //根据路径删除文件及其附件表
      async delAttachment() {
        if (this.delurls.length > 0) {
          await this.delurls.reduce(async (prev, item) => {
            await prev;
            const response = await delAttachmentUrl(item.url)
            console.log(response);
          }, 0);
        }

      },
      //修改路径数组
      seturls(list) {
        if (list == null || list === undefined) {
          list = []
        } else if (typeof (JSON.parse(list)) === 'object') {
          list = Object.values(JSON.parse(list))
        }
        this.urls = list
      },
      //修改删除路径数组
      setdelurls(list) {
        if (list == null || list === undefined) {
          list = []
        } else if (typeof (JSON.parse(list)) === 'object') {
          list = Object.values(JSON.parse(list))
        }
        this.delurls = list
      },
      addurl(url) {
        this.urls.push({ url })
      },
      adduploadfiles(file, from) {
        this.uploadfiles.push({
          file,
          from
        })
      },
      addDelurls(url) {
        this.delurls.push({ url })

      },
      // 清空所有数组
      initAttachment() {
        this.urls = []
        this.uploadfiles = []
        this.delurls = []
      }
    }
  })

export default useAttachmentStore